package com.atguigu.gmall.mq.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.ws.handler.MessageContext;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/mq")
@Slf4j
public class MqController {


   @Autowired
   private RabbitService rabbitService;

   @Autowired
   private RabbitTemplate rabbitTemplate;


   // 消息发送
   //http://cart.gmall.com/8282/mq/sendConfirm
   @GetMapping("sendConfirm")
   public Result sendConfirm() {
      //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      rabbitService.sendMessage("exchange.confirm", "routing.confirm", "来人啦");
      return Result.ok();
   }


   // 测试发送延迟消息
   @GetMapping("sendDeadLettle")
   public Result sendDeadLettle() {
      //声明一个时间戳
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      rabbitService.sendMessage(DeadLetterMqConfig.exchange_dead, DeadLetterMqConfig.routing_dead_1, "延迟了.....");
      //打印一个发送的时间
      System.out.println("消息发送了：\t" + simpleDateFormat.format(new Date()));
      return Result.ok();
   }


   //延迟插件测试  发送消息
   @GetMapping("sendDelay")
   public Result sendDelay(){
      //  如何设置的延迟时间
      rabbitTemplate.convertAndSend(DelayedMqConfig.exchange_delay, DelayedMqConfig.routing_delay, "来人了 关门打狗", new MessagePostProcessor() {
         @Override
         public Message postProcessMessage(Message message) throws AmqpException {
            //在这个位置给消息设置过期时间
            message.getMessageProperties().setDeliveryTag(1000);
            //返回消息
            return null;
         }
      });

      return Result.ok();
   }

}
